package org.lilred.nzbberry.http.cookie;

import java.util.Enumeration;

import javax.microedition.io.HttpConnection;

import org.lilred.nzbberry.http.URL;
import org.lilred.nzbberry.http.cookie.policy.CookiePolicy;

public class CookieManager {
	CookieStore _cookieStore = new CookieStore();

	public void put(HttpConnection connection) throws Exception {
		CookieClump requestCookies = new CookieClump();
		int i = 0;
		while (connection.getHeaderField(i) != null) {
			String headerKey = connection.getHeaderFieldKey(i);
			String cookie = connection.getHeaderField(i);
			if (headerKey.toLowerCase().equals("set-cookie") || headerKey.toLowerCase().equals("set-cookie2")) {
				HttpCookie[] newCookies = HttpCookie.parse(cookie);
				for (int j = 0; j < newCookies.length; j++) {
					newCookies[j].setRequestURL(connection.getURL());
					requestCookies.addCookie(newCookies[j]);
				}
			}
			i++;
		}
		Enumeration e = requestCookies.getCookies();
		while (e.hasMoreElements()) {
			String key = (String) e.nextElement();
			HttpCookie cookie = requestCookies.getCookie(key);
			_cookieStore.addCookie(cookie);
		}
	}

	public String get(String urlString) {
		URL url = new URL(urlString);
		CookieClump applicableCookies = _cookieStore.getCookies(url);
		return (applicableCookies == null) ? "" : applicableCookies.getHeaderString(url);
	}

	public void put(HttpCookie cookie) {
		if (CookiePolicy.ACCEPT_VALID.shouldAccept(cookie)) _cookieStore.addCookie(cookie);
	}
}
